<!-- 计划 -->
<template>
	<el-drawer v-model="isShowDrawer" direction="rtl" :before-close="handleClose" :size="curDrawerSize" :close-on-click-modal="isReadOnly">
		<template #header="{ titleId, titleClass }">
			<div class="zs-drawer-header" :id="titleId" :class="titleClass">
				<i class="icon-b-item zs-icon zs-text-blue zs-space-right-sm"></i>
				<div class="zs-title zs-text-black">证件</div>
			</div>
		</template>

		<template #default>
			<el-container class="zs-drawer-container">
				<el-scrollbar class="zs-drawer-content">
					<!-- card1 -->
					<div class="zs-align-center zs-space-bottom" id="sm-drawer-demo-card-01">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">有效期</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<el-form ref="form1" label-position="right" label-width="140px" :rules="rules.rules1" :model="formData.data">
							<el-form-item label="签发日期：" :prop="formData.data.validityStatus == 0 ? 'validityIssueTime' : ''">
								<el-date-picker clearable :disabled="isReadOnly" v-model="formData.data.validityIssueTime" style="width: 100%" placeholder="请选择" value-format="x" />
							</el-form-item>
							<el-form-item label="有效期：" prop="validityStatus">
								<el-radio-group v-model="formData.data.validityStatus" :disabled="isReadOnly" @change="emptyFiled($event, 'validityStatus')">
									<el-radio :label="1">永久</el-radio>
									<el-radio :label="0">非永久</el-radio>
								</el-radio-group>
							</el-form-item>
							<el-form-item label="有效期至：" prop="validityTime" v-if="formData.data.validityStatus == 0">
								<el-date-picker clearable :disabled="isReadOnly" v-model="formData.data.validityTime" @change="triggerJudgeEffective('validityTime')" style="width: 100%" placeholder="请选择" value-format="x" />
							</el-form-item>
							<el-form-item label="需要提醒：" prop="validityWarnStatus" v-if="formData.data.validityStatus == 0">
								<el-radio-group v-model="formData.data.validityWarnStatus" :disabled="isReadOnly" @change="emptyFiled($event, 'validityWarnStatus')">
									<el-radio :label="1">是</el-radio>
									<el-radio :label="0">否</el-radio>
								</el-radio-group>
							</el-form-item>
							<el-form-item label="提醒时间：" prop="validityWarnNum" v-if="formData.data.validityStatus == 0 && formData.data.validityWarnStatus == 1">
								<el-input class="zs-input-group-md" v-model="formData.data.validityWarnNum" :disabled="isReadOnly" :class="{ 'zs-input-group-white': !isReadOnly }">
									<template #append>
										<div>天</div>
									</template>
								</el-input>
							</el-form-item>
							<el-form-item label="证照失效通知人：" v-if="formData.data.validityStatus == 0 && formData.data.validityWarnStatus == 1">
								<el-select :disabled="isReadOnly" v-model="formData.data.validityIdList" class="zs-full-item" placeholder=" " filterable multiple collapse-tags collapse-tags-tooltip clearable>
									<el-option v-for="item in notifierList" :key="item.id" :label="item.label" :value="item.id" />
								</el-select>
							</el-form-item>
						</el-form>
					</div>

					<!-- card2 -->
					<div class="zs-align-center zs-space-top-lg zs-space-bottom" id="sm-drawer-demo-card-02">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">年审信息</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<el-form ref="form2" label-position="right" label-width="140px" :rules="rules.rules2" :model="formData.data">
							<el-form-item label="是否年审：" prop="annualAuditStatus">
								<el-radio-group v-model="formData.data.annualAuditStatus" :disabled="isReadOnly" @change="emptyFiled($event, 'annualAuditStatus')">
									<el-radio :label="1">是</el-radio>
									<el-radio :label="0">否</el-radio>
								</el-radio-group>
							</el-form-item>
							<el-form-item label="年审时间：" prop="annualAuditTime" v-if="formData.data.annualAuditStatus == 1">
								<el-date-picker clearable :disabled="isReadOnly" v-model="formData.data.annualAuditTime" @change="triggerJudgeEffective('annualAuditTime')" style="width: 100%" placeholder="请选择" value-format="x" />
							</el-form-item>
							<el-form-item label="需要提醒：" prop="annualWarnStatus" v-if="formData.data.annualAuditStatus == 1">
								<el-radio-group v-model="formData.data.annualWarnStatus" :disabled="isReadOnly" @change="emptyFiled($event, 'annualWarnStatus')">
									<el-radio :label="1">是</el-radio>
									<el-radio :label="0">否</el-radio>
								</el-radio-group>
							</el-form-item>
							<el-form-item label="提醒时间：" prop="annualWarnNum" v-if="formData.data.annualAuditStatus == 1 && formData.data.annualWarnStatus == 1">
								<el-input class="zs-input-group-md" v-model="formData.data.annualWarnNum" :disabled="isReadOnly" :class="{ 'zs-input-group-white': !isReadOnly }">
									<template #append>
										<div>天</div>
									</template>
								</el-input>
							</el-form-item>
							<el-form-item label="年审通知人：" v-if="formData.data.annualAuditStatus == 1 && formData.data.annualWarnStatus == 1">
								<el-select :disabled="isReadOnly" v-model="formData.data.annualIdList" class="zs-full-item" placeholder=" " filterable multiple collapse-tags collapse-tags-tooltip clearable>
									<el-option v-for="item in notifierList" :key="item.id" :label="item.label" :value="item.id" />
								</el-select>
							</el-form-item>
						</el-form>
					</div>
				</el-scrollbar>
				<hsDocWrapper :nodeList="curNodeList" />
			</el-container>
		</template>

		<template v-if="handleType != 'info'" #footer>
			<div>
				<el-button class="zs-btn-md zs-btn-primary" @click="doConfirm">提交</el-button>
			</div>
		</template>
	</el-drawer>
</template>

<script setup>
	import { licenseSettingAddApi, licenseSettingInfoApi, notifierListApi } from '@/api/license.js';
	import { ElMessage } from 'element-plus';
	import { ref, reactive, watch, nextTick } from 'vue';
	import { useStore } from 'vuex';
	import { deepClone } from '@/utils/publicUtils';
	import { judgeDIffTime } from '@/utils/formRules';

	const props = defineProps({
		isShow: { type: Boolean, default: false },
		isReadOnly: { type: Boolean, default: true },
		handleType: { type: String, default: '' },
		currentRow: { type: Object },
	});

	let store = useStore();
	const curDrawerSize = ref(store.state.uiDrawerSize);

	const emit = defineEmits(['close']);
	let formData = reactive({ data: { validityTime: '', validityStatus: 1, validityWarnStatus: 1, annualAuditStatus: 1, annualWarnStatus: 1, annualWarnNum: '', validityWarnNum: '', validityIdList: [], annualIdList: [] } });

	const form1 = ref({
		returnModel() {
			return formData.data;
		},
		clearValidate(filedName) {
			form1.value.clearValidate(filedName);
		},
	});
	const form2 = ref();

	let isShowDrawer = ref(props.isShow);

	const rules = reactive({
		rules1: {
			validityIssueTime: [
				{ required: true, message: '请选择签发日期', trigger: 'change' },
				{ validator: judgeDIffTime(form1.value, 'validityIssueTime', 'validityTime', '签发日期', '有效期'), trigger: ['blur', 'change'] },
			],
			validityStatus: [{ required: true, message: '请选择有效期', trigger: 'change' }],
			validityTime: [
				{ required: true, message: '请选择有效期至', trigger: 'change' },
				{ validator: judgeDIffTime(form1.value, 'validityIssueTime', 'validityTime', '签发日期', '有效期'), trigger: ['blur', 'change'] },
			],
			validityWarnStatus: [{ required: true, message: '请选择需要提醒', trigger: 'change' }],
			validityWarnNum: [
				{ required: true, message: '请输入提醒时间', trigger: 'blur' },
				{ validator: twoDecimalPlaces(), trigger: ['change', 'blur'] },
				{ validator: judgeEffective, trigger: ['change', 'blur'] },
			],
		},
		rules2: {
			annualAuditStatus: [{ required: true, message: '请选择是否年审', trigger: 'change' }],
			annualAuditTime: [{ required: true, message: '请选择年审时间', trigger: 'change' }],
			annualWarnStatus: [{ required: true, message: '请选择需要提醒', trigger: 'change' }],
			annualWarnNum: [
				{ required: true, message: '请输入提醒时间', trigger: 'blur' },
				{ validator: twoDecimalPlaces(), trigger: ['change', 'blur'] },
				{ validator: judgeEffective, trigger: ['change', 'blur'] },
			],
		},
	});

	const curNodeList = ref([
		{ name: '有效期', id: 'sm-drawer-demo-card-01' },
		{ name: '年审信息', id: 'sm-drawer-demo-card-02' },
	]);

	watch(
		() => props.isShow,
		(newVal, oldVal) => {
			isShowDrawer.value = newVal;
			nextTick(() => {
				newVal && ['info', 'edit'].includes(props.handleType) && getInfo(props.currentRow?.id);
				getNotifierList();
			});
		},
	);

	//详情
	const getInfo = async id => {
		let res = await licenseSettingInfoApi({ id });
		if (res.data.code !== 200) return;
		res.data.data.annualWarnStatus = res.data.data.annualWarnStatus ? res.data.data.annualWarnStatus : 0;
		res.data.data.validityWarnStatus = res.data.data.validityWarnStatus ? res.data.data.validityWarnStatus : 0;
		res.data.data.validityStatus = res.data.data.validityStatus ? res.data.data.validityStatus : 0;
		res.data.data.annualAuditStatus = res.data.data.annualAuditStatus ? res.data.data.annualAuditStatus : 0;
		formData.data = Object.assign(res.data.data);
	};

	//失效负责人 | 年审通知人 数据源
	const notifierList = ref([]);
	const getNotifierList = async () => {
		let res = await notifierListApi({ id: props.currentRow.id });
		res.data.data.forEach(item => {
			item.label = `${item.realName}(${item.phoneNum})`;
		});
		notifierList.value = res.data.data || [];
	};

	//提交
	const doConfirm = async () => {
		const forms = [form1, form2];
		const validatePromises = forms.map(form => new Promise(resolve => form.value.validate(resolve)));
		Promise.all(validatePromises).then(async results => {
			const isValid = results.every(valid => valid);
			if (!isValid) return;
			let params = deepClone(formData.data);
			params.id = props.currentRow.id;
			params.annualWarnStatus = params.annualWarnStatus ? params.annualWarnStatus : 0;
			params.validityWarnStatus = params.validityWarnStatus ? params.validityWarnStatus : 0;

			let res = await licenseSettingAddApi(params);
			if (res.data.code == 200) {
				ElMessage({
					message: '提交成功',
					type: 'success',
				});
				isShowDrawer.value = false;
				emit('close', { isShow: false, isRefresh: true });
			}
		});
	};

	//关闭抽屉
	const handleClose = done => {
		emit('close', { isShow: false });
		done();
	};

	//选择否清空相关字段
	const emptyFiled = (val, type) => {
		let clearFiledArr = [];
		if (type == 'annualAuditStatus') {
			clearFiledArr = ['annualAuditTime', 'annualWarnStatus', 'annualWarnNum', 'annualIdList'];
		} else if (type == 'annualWarnStatus') {
			clearFiledArr = ['annualWarnNum', 'annualIdList'];
		} else if (type == 'validityStatus') {
			clearFiledArr = ['validityTime', 'validityWarnStatus', 'validityWarnNum', 'validityIdList'];
		} else if (type == 'validityWarnStatus') {
			clearFiledArr = ['validityWarnNum', 'validityIdList'];
		}
		if (type == 'validityStatus') {
			val && clearFiled(clearFiledArr);
		} else {
			!val && clearFiled(clearFiledArr);
		}
	};

	const clearFiled = arr => {
		let typeArr = ['annualIdList', 'validityIdList']
		arr.forEach(filed => {
			formData.data[filed] = typeArr.includes(filed) ? [] : '';
		});
	};

	// 校验有效期
	function judgeEffective(rule, value, callback) {
		let effectList = ['validityTime', 'validityWarnNum'];
		let yearLimitList = ['annualAuditTime', 'annualWarnNum'];
		let target = effectList.includes(rule.field) ? effectList : yearLimitList;
		let nowTime = new Date().getTime();
		let oneDayTime = 60 * 1000 * 60 * 24;
		let diffTime = formData.data[target[0]] - oneDayTime * formData.data[target[1]];
		if (diffTime < nowTime) {
			callback(new Error('提醒时间小于当前时间'));
		} else {
			callback();
		}
	}

	const triggerJudgeEffective = filedName => {
		if (filedName === 'validityTime') {
			formData.data.validityWarnNum && form1.value.validateField('validityWarnNum');
		} else {
			formData.data.annualWarnNum && form2.value.validateField('annualWarnNum');
		}
	};

	// 校验整数
	function twoDecimalPlaces() {
		return (rule, value, callback) => {
			let reg = /^(?:[0-9]|[1-9][0-9]?|1[0-9]{2}|2[0-9]{2}|3[0-5][0-9]|36[0-5]|0)$/;
			if (reg.test(value)) {
				callback();
			} else {
				callback(new Error('支持0-365的正整数'));
			}
		};
	}

	// 时间校验
	function endDateValid(rule, value, callback) {
		let diffVal = (formData.data.validityTime || 0) - (formData.data.validityIssueTime || 0);
		if (formData.data.validityIssueTime && formData.data.validityTime) {
			if (diffVal < 0) {
				callback(new Error('有效期不能小于签发日期'));
			} else {
				form1.value.clearValidate('validityIssueTime');
				callback();
			}
		}
	}
</script>
